package network.chat;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;

/**
 * @author mubei
 * @date 2021/12/5
 * @description 聊天接收窗口
 */
public class TalkReceive {

    DatagramSocket socket = null;

    private int port;
    private String msgFrom;

    public TalkReceive(int port,String msgFrom) {
        this.port = port;
        this.msgFrom = msgFrom;
        try {
            init();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void init() throws Exception {
        socket = new DatagramSocket(this.port);
    }

    public void run() {

        while (true) {
            String s = null ;
            try {
                byte bytes[] = new byte[1024];
                DatagramPacket packet = new DatagramPacket(bytes, 0, bytes.length);
                socket.receive(packet);
                s = new String(packet.getData(), 0, packet.getLength());
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                if (s.equals("bye")) {
                    break;
                }
                System.out.println(msgFrom+" "+s);
            }

        }
        socket.close();
    }
}
